package com.qijian.maindata.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.maindata.domain.InspectionItem;
import com.qijian.maindata.domain.InspectionItemDetail;
import com.qijian.maindata.domain.InspectionSchemeDetails;
import com.qijian.maindata.domain.vo.InspectionItemVo;
import com.qijian.maindata.mapper.InspectionItemMapper;
import com.qijian.maindata.mapper.InspectionSchemeDetailsMapper;
import com.qijian.maindata.service.IInspectionItemDetailService;
import com.qijian.maindata.service.IInspectionItemService;
import com.qijian.tool.domain.Storage;
import com.qijian.tool.domain.query.StorageQuery;
import com.qijian.tool.service.IStorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 检验项-新Service业务层处理
 *
 * @author qijian
 * @date 2024-02-02
 */
@Service
@RequiredArgsConstructor
public class InspectionItemServiceImpl extends ServiceImpl<InspectionItemMapper, InspectionItem> implements IInspectionItemService {

    private final InspectionItemMapper inspectionItemMapper;

    private final IInspectionItemDetailService itemDetailService;

    private final IStorageService storageService;

    private final InspectionSchemeDetailsMapper inspectionSchemeDetailsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveItemVo(InspectionItemVo itemVo) {
        if(CollUtil.isEmpty(itemVo.getDetails())){
            throw new ServiceException("检验项明细不能为空");
        }
        if(Objects.isNull(itemVo.getId())){
            //新增
            if(StrUtil.isBlank(itemVo.getExamineCode())){
                itemVo.setExamineCode("JYX-" + String.format("%06d", inspectionItemMapper.countWithDel()+1));
            }
            this.save(itemVo);
        }else{
            //修改
            Long count = inspectionSchemeDetailsMapper.selectCount(new LambdaQueryWrapper<InspectionSchemeDetails>().eq(InspectionSchemeDetails::getItemId, itemVo.getId()));
            if(count>0L){
                throw new ServiceException("E01:检验项被检验方案使用,无法修改");
            }
            this.updateById(itemVo);
            itemDetailService.remove(new LambdaQueryWrapper<InspectionItemDetail>().eq(InspectionItemDetail::getMainItemId,itemVo.getId()));
        }
        //保存明细
        itemVo.getDetails().forEach(i->{
            i.setId(null);
            //0,0,-1 时
            if((StrUtil.equals("0",i.getMaxValue()) || StrUtil.isBlank(i.getMaxValue()) || StrUtil.equals("/",i.getMaxValue()))
                    && (StrUtil.equals("0",i.getMinValue()) || StrUtil.isBlank(i.getMinValue()) || StrUtil.equals("/",i.getMinValue()) )
                    &&StrUtil.equals("-1",i.getDefaultValue())){
                //同时将最大最小值设置成/
                i.setMinValue("/");
                i.setMaxValue("/");
                i.setIsText(false);
            }
            i.setMainItemId(itemVo.getId());
        });
        itemDetailService.saveBatch(itemVo.getDetails());
        //保存附件
        if(CollUtil.isNotEmpty(itemVo.getFiles())){
            itemVo.getFiles().forEach(action -> {
                action.setClassTable(InspectionItem.class.getSimpleName());
                action.setClassId(itemVo.getId());
                action.setClassify(1); //1 为检验项的附件类型
            });
            storageService.updateBatchById(itemVo.getFiles());
        }
        //保存图片

        return true;
    }

    @Override
    public InspectionItemVo getInfo(Long id) {
        InspectionItem item = this.getById(id);
        if(Objects.isNull(item)){
            return new InspectionItemVo();
        }
        List<InspectionItemDetail> details = itemDetailService.list(new LambdaQueryWrapper<InspectionItemDetail>().eq(InspectionItemDetail::getMainItemId, id));
        //文件
        StorageQuery query = new StorageQuery();
        query.setClassId(id);
        query.setClassTable(InspectionItem.class.getSimpleName());
        query.setClassify(1);
        List<Storage> files = storageService.list(WhereEntityTool.invoke(query));
        InspectionItemVo inspectionItemVo = new InspectionItemVo();
        BeanUtils.copyProperties(item,inspectionItemVo);
        inspectionItemVo.setFiles(files);
        inspectionItemVo.setDetails(details);
        //检验项图片
        query.setClassify(2);
        List<Storage> list = storageService.list(WhereEntityTool.invoke(query));
        if(CollUtil.isNotEmpty(list)){
            inspectionItemVo.setStorage(list.get(0));
        }
        return inspectionItemVo;
    }

    @Override
    public boolean deleteMains(List<Long> mainIds) {
//        mainIds.forEach(id->{
//            if(ids.contains(id)){
//                throw new ServiceException("E01:默认项目不能删除");
//            }
//        });
        if(CollUtil.isEmpty(mainIds)){
            throw new ServiceException("E01:未选择删除的数据!");
        }
        //查询检验项是否被使用,被使用无法删除
        Long count = inspectionSchemeDetailsMapper.selectCount(new LambdaQueryWrapper<InspectionSchemeDetails>().in(InspectionSchemeDetails::getItemId, mainIds));
        if(count>0L){
            throw new ServiceException("E01:检验项被检验方案使用,无法删除");
        }
        //删除主表同时删除明细
        this.removeByIds(mainIds);
        this.itemDetailService.remove(new LambdaQueryWrapper<InspectionItemDetail>().in(InspectionItemDetail::getMainItemId,mainIds));
        return true;
    }

    @Override
    public List<InspectionItem> getBySchemeId(Long schemeId) {
        return baseMapper.selectBySchemeId(schemeId);
    }
}
